﻿using System.IO;

namespace GFramework.Netwrok
{
    public abstract class MessagePacker : Leaf, IMessagePacker, IAwake<IMessagePacker>
    {
        private IMessagePacker m_messagePacker;
        public void Awake(IMessagePacker messagePacker)
        {
            m_messagePacker = messagePacker;
        }

        public IMessage DeserializePacket(IMessageHeader packetHeader, Stream source)
        {
            if(m_messagePacker == null)
            {
                throw new GException("MessagePacker is nil!");
            }
            return m_messagePacker.DeserializePacket(packetHeader, source);
        }

        public IMessageHeader DeserializePacketHeader(Stream source)
        {
            if (m_messagePacker == null)
            {
                throw new GException("MessagePacker is nil!");
            }
            return m_messagePacker.DeserializePacketHeader(source);
        }

        public bool Serialize<T>(T packet, Stream destination) where T : IMessage
        {
            if (m_messagePacker == null)
            {
                throw new GException("MessagePacker is nil!");
            }
            return m_messagePacker.Serialize<T>(packet, destination);
        }
    }
}
